package com.ruoyi.module.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.module.domain.Address;
import com.ruoyi.module.mapper.AddressMapper;
import com.ruoyi.module.service.IAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户收货地址Service业务层处理
 *
 * @author fubojin
 * @date 2024-12-06
 */
@Service
public class AddressServiceImpl implements IAddressService
{
    @Autowired
    private AddressMapper addressMapper;

    /**
     * 查询用户收货地址
     *
     * @param id 用户收货地址主键
     * @return 用户收货地址
     */
    @Override
    public Address selectAddressById(Long id)
    {
        return addressMapper.selectAddressById(id);
    }

    /**
     * 查询用户收货地址列表
     *
     * @param address 用户收货地址
     * @return 用户收货地址
     */
    @Override
    public List<Address> selectAddressList(Address address)
    {
        return addressMapper.selectAddressList(address);
    }

    /**
     * 新增用户收货地址
     *
     * @param address 用户收货地址
     * @return 结果
     */
    @Override
    public int insertAddress(Address address)
    {
        address.setCreateTime(DateUtils.getNowDate());
        setDefault(address);
        return addressMapper.insertAddress(address);
    }

    /**
     * 修改用户收货地址
     *
     * @param address 用户收货地址
     * @return 结果
     */
    @Override
    public int updateAddress(Address address)
    {
        address.setUpdateTime(DateUtils.getNowDate());
        setDefault(address);
        return addressMapper.updateAddress(address);
    }

    /**
     * 修改默认地址
     * @param address
     */
    private void setDefault(Address address) {
        if (address != null) {
            Integer isDefault = address.getIsDefault();
            if (isDefault == 1) {
                List<Address> addressList = addressMapper.listByUserId(address.getUserId());
                if (!addressList.isEmpty()) {
                    addressList.forEach(c -> c.setIsDefault(0));
                    addressList.forEach(this::updateAddress);
                }
            }
        }
    }

    /**
     * 批量删除用户收货地址
     *
     * @param ids 需要删除的用户收货地址主键
     * @return 结果
     */
    @Override
    public int deleteAddressByIds(Long[] ids)
    {
        return addressMapper.deleteAddressByIds(ids);
    }

    /**
     * 删除用户收货地址信息
     *
     * @param id 用户收货地址主键
     * @return 结果
     */
    @Override
    public int deleteAddressById(Long id)
    {
        return addressMapper.deleteAddressById(id);
    }
}
